import { apiRoot } from "./config";
import { getToken } from '.';

function ajax(opt) {
  let token = getToken();
  let def = {
    method: 'GET',
    beforeSend: jqXHR => jqXHR.setRequestHeader("Authorization", token),
  };
  opt = $.extend({}, def, opt);
  opt.url = apiRoot + opt.url;
  let dfd = $.Deferred();
  let jqXHR = $.ajax(opt);
  jqXHR.done(d => {
    switch (d.code) {
      case 200:
        dfd.resolve(d.data);
        break;
      case 403:
        alert(d.msg);
        dfd.reject(d.msg);
        location.replace('login.html');
        break;
      default:
        alert(d.msg);
        dfd.reject(d.msg);
    }
  }).fail((xhr, errorType, error) => {
    alert(error);
    dfd.reject(xhr, errorType, error);
  });
  dfd.abort = () => jqXHR.abort();
  return dfd;
}

function parse_args(args, obj) {
  let settings = {};
  if (typeof args[0] == 'object') {
    $.extend(settings, args[0]);
  } else {
    if (args[0]) settings.url = args[0];
    if (args[1]) settings.data = args[1];
    if (args[2]) settings.success = args[2];
    if (args[3]) settings.dataType = args[3];
  }
  return $.extend(settings, obj);
}

export default ajax;
export function get() {
  let opt = parse_args(arguments, { method: 'GET' });
  return ajax(opt);
};
export function post() {
  let opt = parse_args(arguments, { method: 'POST' });
  return ajax(opt);
};
export function del() {
  let opt = parse_args(arguments, { method: 'DELETE' });
  return ajax(opt);
};
export function put() {
  let opt = parse_args(arguments, { method: 'PUT' });
  return ajax(opt);
};
